﻿using GDGeek;
using MrPP.UX;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MrPP.SerriedCabinet
{
    public class BoxRoot : GDGeek.Singleton<BoxRoot>
    {


        [SerializeField]
        private GameObject _mark;
        [SerializeField]
        private BoxManager _manager;
        [SerializeField]
        private CellManager _cellManager;
        [SerializeField]
        private BoxModel _model;
        public CellManager cellManager
        {
            get
            {
                return _cellManager;
            }
        }
        public BoxManager manager {
            get {
                return _manager;
            }
        }
        public void doLight(CabinetGroup.ItemData last, CabinetGroup.ItemData next) {
          
            if (next.type != Box.Type.None)
            {
                _manager.highlight(next);
            }
            else {
                _manager.lowlight();
            }
        }
        public void Start() {

            
            if (CabinetGroup.IsInitialized)
            {
                if (CabinetGroup.Instance.initialized)
                {
                    init();
                }else
                {

                    CabinetGroup.Instance.onSetup += init;

                }
            }
            if (_model != null) {

                _model.onLight += doLight;
            }
        }
       
        [SerializeField]
        private Transform _target;
        public bool inside(Vector3 position) {
            if (_collider) {
                var d = position - (_collider.transform.position + _collider.center);
                if (Mathf.Abs(d.x) <= (_collider.size.x/2f) && Mathf.Abs(d.y) <= (_collider.size.y / 2f) && Mathf.Abs(d.z) <= (_collider.size.z / 2f))
                {
                    return true;

                }
                else {

                    return false;
                }
            }
            return false;
        } 
           
        void OnDestroy()
        {
            if (CabinetGroup.IsInitialized)
            {
                CabinetGroup.Instance.onSetup -= init;
            }
        }
        private void setup(BoxManager.Data data) {

            _manager.setup(data);
        }
        [SerializeField]
        private Transform _boxs;
        [SerializeField]
        private BoxCollider _collider;
        public void init() {
            setup(CabinetGroup.Instance.data.cabinets);
            BoxColliderCreater creater = _boxs.gameObject.AskComponent<BoxColliderCreater>();
            creater.onDestory += delegate
            {
                _collider = _boxs.gameObject.GetComponent <BoxCollider>();
                _collider.enabled = false;
            };   

        }
    }
}